const express = require('express')
//创建服务器
const app = express.Router()
const { getMd, getAllArticles, getArticleById } = require('../dataBase/api')
/* GET users listing. */
app.get('/', function (req, res, next) {
    getMd().then((data) => {
        res.json({ data })
    })
});

app.get('/getAllArticles', function (req, res, next) {
    getAllArticles().then((data) => {
        res.json({ data })
    }).catch(error => {
        res.status(500).json({ error: '获取文章列表失败' });
    });
});

app.get('/getArticleById/:id', function (req, res, next) {
    const articleId = req.params.id;
    console.log('Fetching article with ID:', articleId);
    
    getArticleById(articleId).then((data) => {
        res.json({ data })
    }).catch(error => {
        console.error('Error fetching article:', error);
        res.status(500).json({ error: '获取文章详情失败' });
    });
});

// 获取文章列表
app.get('/list', (req, res) => {
  // 设置响应头
  res.header('Access-Control-Allow-Credentials', 'true');
  res.header('Access-Control-Allow-Origin', req.headers.origin);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type,Authorization');

  try {
    // 你的数据处理逻辑
    const articles = [
      {
        id: 1,
        title: '示例文章',
        // ... 其他字段
      }
    ];
    res.json(articles);
  } catch (error) {
    res.status(500).json({ error: '获取文章列表失败' });
  }
});

module.exports = app;